package com.zprmb.udzt;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.view.WebViewDialog;

import java.util.HashMap;
import java.util.Map;


@SuppressLint("SetJavaScriptEnabled")
public class V4WebViewRegisterActivity2 extends BaseActivity implements OnClickListener {

    private ImageView iv_v4_web_back;
    private TextView tv_v4_web_title;
    private String title;
    private String ref = "";
    private String url;
    private boolean isOnPause = false;

    String version = "";
    //    private WebView v4_webview;
    private WebView v4_webview;

    private static final String SHARE = "um";
    private RelativeLayout rl_back;
    //	private ProgressBar bar;
    private boolean back = false;
    private WebViewDialog dialog;
    Map<String, String> extraHeaders;
    private SharedPreferences sha;
    int flag;
    private View web_head_view;
    private View title_view;

    private ImageView iv_v4_nonetwork;

    private ImageView img_share;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_aggrement2);
        setImmersionStatus();


        v4_webview = (WebView) findViewById(R.id.v4_webview);
        title_view = (View) findViewById(R.id.title_view);
//		Toast.makeText(this, "第二页", Toast.LENGTH_SHORT).show();
        BbtApplication.getInstance().addActvity(this);
        Intent intent = getIntent();
        dialog = new WebViewDialog(this);
        title = intent.getStringExtra("title");
        url = intent.getStringExtra("url");
        ref = getShare().getString("usercode", "");
        version = getAppVersion();
        LogUtils.e(V4WebViewRegisterActivity2.this, url);
        // url = "account/invest/8F759CC2-65DB-11E5-AE96-5254002EAABD/contract";
        sha = getSharedPreferences("config", MODE_PRIVATE);
        iv_v4_nonetwork = (ImageView) findViewById(R.id.iv_v4_nonetwork);
        flag = getIntent().getIntExtra("flag", 0);
        img_share = (ImageView) findViewById(R.id.img_share);
        img_share.setVisibility(View.GONE);
        if (flag == 1) {

            v4_webview.loadUrl(url + "&token=" + getToken(), extraHeaders);

        } else {
            v4_webview.loadUrl(Constant.URL + url + "&token=" + getToken(), extraHeaders);
            Log.e("url", Constant.URL + url + "&token=" + getToken());
            // v4_webview.loadUrl("http://192.168.40.177:8085/landing/mWelfare8888-2016");
        }
        v4_webview.resumeTimers();
        initView();
        if (!network()) {
            iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

            v4_webview.setVisibility(View.GONE);
            title_view.setVisibility(View.VISIBLE);

            web_head_view.setVisibility(View.GONE);

        } else {
            iv_v4_nonetwork.setVisibility(View.GONE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

            v4_webview.setVisibility(View.VISIBLE);
            title_view.setVisibility(View.VISIBLE);
            web_head_view.setVisibility(View.GONE);
            initData();

        }


    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub

        super.onDestroy();

        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
        BbtApplication.getInstance().removeActvity(this);

        setContentView(R.layout.viewxml);
    }


    @Override
    protected void onPause() {
        super.onPause();

        if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB && url.contains("video")) {
            v4_webview.onPause(); // 暂停网页中正在播放的视频
        }
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, arg2);
        if (arg2 != null) {
//			reload=arg1;
//			Log.e("arg1intent", arg2.getIntArrayExtra("resultcode")+"");
            if (arg1 == 1) {

//				String url=geturl().substring(1, geturl().length());
//				Log.e("url", url);
//			v4_webview.loadUrl(Constant.URL+url+"&token="+getURLToken());
                v4_webview.loadUrl(url + "&token=" + getToken(), extraHeaders);
                v4_webview.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        v4_webview.clearHistory();
                    }
                }, 1000);

            } else if (arg1 == 2) {
                v4_webview.reload();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (v4_webview.canGoBack()) {
                v4_webview.goBack();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

//    		if (newProgress == 100) {
//				dialog.dismiss();
//			} else {
//				if (dialog.isShowing() == false) {
//					dialog.show();
//				}
//
//			}
            super.onProgressChanged(view, newProgress);
        }
    };
    private boolean loadError = false;

    private void initData() {
        extraHeaders = new HashMap<String, String>();
        extraHeaders.put("token", getToken());
        v4_webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//				Log.e("myurl", url+"");
                if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
                    if (url.contains("?")) {
                        url = url + "&app=true&token=" + getURLToken();

                    } else {
                        url = url + "?app=true&token=" + getURLToken();

                    }

                    view.loadUrl(url, extraHeaders);
                }

                // else if(url.indexOf("tel")==0){
                // view.loadUrl(url,extraHeaders);
                // return true;
                // }
                // view.loadUrl(Constant.URL_NEW+url,extraHeaders);
                // view.loadUrl("http://docs.google.com/gview?embedded=true&url=http://www.navicat.com.cn/manual/pdf_manual/cn/navicat/rv_manual/rviewer_cs.pdf");
                return true;
            }

            @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebViewClient.a a) {
                loadError = true;
                iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                v4_webview.setVisibility(View.GONE);
                title_view.setVisibility(View.VISIBLE);

                web_head_view.setVisibility(View.GONE);
                super.onReceivedError(webView, webResourceRequest, a);
            }

            /*     @Override
            public void onReceivedError(com.tencent.smtt.sdk.WebView view, WebResourceRequest request, WebResourceError error) {

                loadError = true;
                iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                v4_webview.setVisibility(View.GONE);
                title_view.setVisibility(View.VISIBLE);

                web_head_view.setVisibility(View.GONE);
            }*/

        /*    @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, SslError error) {
                // TODO Auto-generated method stub
//				super.onReceivedSslError(view, handler, error);
                handler.proceed();
            }*/

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {

                super.onReceivedSslError(webView, sslErrorHandler, sslError);
            }

            //			}


            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                v4_webview.setVisibility(View.GONE);
                title_view.setVisibility(View.VISIBLE);

                web_head_view.setVisibility(View.GONE);
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                if (dialog != null & dialog.isShowing() == false) {
                    dialog.show();
                }

                loadError = false;
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub

                // TODO Auto-generated method stub
                try {

                    if (dialog != null & dialog.isShowing() == true) {
                        dialog.dismiss();

                    }
                   /* if (!loadError) {//当网页加载成功的时候判断是否加载成功
                        iv_v4_nonetwork.setVisibility(View.GONE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView
                        v4_webview.setVisibility(View.VISIBLE);
                    } else { //加载失败的话，初始化页面加载失败的图，然后替换正在加载的视图页面
                        iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                        v4_webview.setVisibility(View.GONE);
                        title_view.setVisibility(View.VISIBLE);

                        web_head_view.setVisibility(View.GONE);
                    }*/

                } catch (Exception e) {

                }
                title_view.setVisibility(View.VISIBLE);
                web_head_view.setVisibility(View.GONE);
                super.onPageFinished(view, url);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view,
                                                              String url) {
                // TODO Auto-generated method stub
                return super.shouldInterceptRequest(view, url);

            }
        });
    /*    v4_webview.clearCache(true);

        v4_webview.setWebChromeClient(chromeClient);

        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
//		v4_webview.getSettings().setDomStorageEnabled(true);
        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4_webview.addJavascriptInterface(new JsInterfaces(this),
                "AndroidWebView");
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);

        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);

        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();
        try {
            if (VERSION.SDK_INT >= VERSION_CODES.KITKAT_WATCH) {
                v4_webview.getSettings().setMixedContentMode(v4_webview.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);
            }

        } catch (Exception e) {
            // TODO: handle exception
        }



        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");*/
        v4_webview.clearCache(true);

        v4_webview.setWebChromeClient(chromeClient);


        // 重新设置websettings WebSettings s = wb.getSettings();
        // s.setBuiltInZoomControls(true);
        // s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);

        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
//		v4_webview.getSettings().setDomStorageEnabled(true);
        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4_webview.addJavascriptInterface(new JsInterfaces(V4WebViewRegisterActivity2.this),
                "AndroidWebView");
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        // This next one is crazy. It's the DEFAULT location for your app's
        // cache
        // But it didn't work for me without this line.
        // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();
        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");
        if (v4_webview.getX5WebViewExtension() != null) {
            v4_webview.getX5WebViewExtension().setVerticalTrackDrawable(null);
        }

    }

    @Override
    public void onClick(View v) {

    }


    private class JsInterfaces {
        private Context mContext;

        public JsInterfaces(Context context) {
            this.mContext = context;
        }

        // 在js中调用window.AndroidWebView.showInfoFromJs(name)，便会触发此方法。
        @JavascriptInterface
        public void pleaseLogin(String name) {
            Intent intent = new Intent(V4WebViewRegisterActivity2.this,
                    V6LoginActivity.class);
            intent.putExtra("close", 1);
            intent.putExtra("web", 1);
            startActivityForResult(intent, 1);
            Editor editor = sha.edit();
            editor.putString("url", url);
            editor.commit();
        }


        @JavascriptInterface
        public void finish(int type) {

            if (type == 0) {
                V4WebViewRegisterActivity2.this.finish();
                return;

            }
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    if (v4_webview.canGoBack()) {
                        v4_webview.goBack();
                    } else {
                        if (dialog != null) {


                        }
                        Intent intent = new Intent();
                        setResult(1, intent);
                        V4WebViewRegisterActivity2.this.finish();
                    }
                }
            });


        }

    }


    private void initView() {
        iv_v4_web_back = (ImageView) findViewById(R.id.img_back);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);


        web_head_view = (View) findViewById(R.id.web_head_view);

        title_view.setVisibility(View.VISIBLE);
        web_head_view.setVisibility(View.GONE);

        rl_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (v4_webview.canGoBack()) {
                    v4_webview.goBack();
                } else {
                    finish();
                }
            }
        });
        iv_v4_web_back.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (v4_webview.canGoBack()) {
                    v4_webview.goBack();
                } else {
                    finish();
                }
            }
        });
        tv_v4_web_title = (TextView) findViewById(R.id.tv_title);
        tv_v4_web_title.getPaint().setFakeBoldText(true);
        tv_v4_web_title.setText(title);

        tv_v4_web_title.setText(title);


        v4_webview = (WebView) findViewById(R.id.v4_webview);
        iv_v4_nonetwork.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                // TODO Auto-generated method stub
//
                if (!network()) {
                    iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                    v4_webview.setVisibility(View.GONE);
                    title_view.setVisibility(View.VISIBLE);

                    web_head_view.setVisibility(View.GONE);
                    Toast.makeText(V4WebViewRegisterActivity2.this, "当前无网络", Toast.LENGTH_SHORT).show();
                } else {
                    iv_v4_nonetwork.setVisibility(View.GONE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                    v4_webview.setVisibility(View.VISIBLE);
                    title_view.setVisibility(View.VISIBLE);
                    web_head_view.setVisibility(View.GONE);
//                    initData();
                    v4_webview.reload();
                    initData();
                }

            }
        });
    }


    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }


}
